package org.visionlibrary.image.geomtric.util;

import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * Klasa narzedziowa zawierajaca dodatkowe metody ulatwiajace wyswietlanie i
 * rysowanie obrazow. 
 */
public class TestUtils {
	public static void showImage(final BufferedImage img, final String title) {
		showImage(img, title, true);
	}

	public static void showImage(final BufferedImage img, final String title,
			final boolean wait) {
		final JFrame frame = new JFrame(title);
		frame.setSize(img.getWidth() + 20, img.getHeight() + 50);
		JPanel drawPanel = new JPanel() {

			private static final long serialVersionUID = 1L;

			public void paint(Graphics g) {
				g.drawImage(img, 0, 0, null);
			}
		};
		drawPanel.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				synchronized (frame) {
					if (wait) {
						frame.notifyAll();
					} else {
						frame.dispose();
					}
				}
			}

		});
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				synchronized (frame) {
					if (wait) {
						frame.notifyAll();
					} else {
						frame.dispose();
					}
				}
			}
		});

		frame.setContentPane(drawPanel);
		frame.setVisible(true);

		if (wait) {
			synchronized (frame) {
				try {
					frame.wait();
				} catch (InterruptedException e1) {
					new RuntimeException(e1);
				}
			}
			frame.dispose();
		}
	}

	public static void showImage(final BufferedImage img) {
		showImage(img, "Preview", true);
	}
}
